package com.lvtu.monitor.module.web.exception;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lvmama.com.lvtu.common.utils.DateUtil;
import com.lvtu.monitor.module.web.module.ResultHandler;
import com.lvtu.monitor.module.web.module.po.IndexException;
import com.lvtu.monitor.utils.Constants;
import com.lvtu.monitor.utils.ElasticUtils;

/**
 * @Title: ExQueryAction.java
 * @Package com.lvtu.monitor.module.web.exception
 * @Description: TODO
 * @author dengcheng
 * @date 2015-5-21 下午5:06:32
 * @version V1.0.0
 */
@Controller
// 在类上面定义，表明该类为控制器，返回字符串与redirect:xxx
@RequestMapping("/exQuery")
public class ExQueryAction {

	@RequestMapping(value = "/toqueryEx")
	public String toqueryEx() {
		return "/exmonitor/ex_list";
	}

	@RequestMapping(value = "/loadEx")
	@ResponseBody
	public ResultHandler loadEx(String udid, String method, String lvsessionid,
			String ip, int page, int rows, String queryDate) {
		QueryBuilder queryBuilder = null;
		FilterBuilder filterBuilder = null;
		if (!StringUtils.isEmpty(udid)) {
			queryBuilder = QueryBuilders.matchQuery("udid", udid);
		}

		
		if (!StringUtils.isEmpty(lvsessionid)) {
			queryBuilder = QueryBuilders.matchQuery("lvsessionid", lvsessionid);
		}
		
		
		if (!StringUtils.isEmpty(method)) {
			queryBuilder = QueryBuilders.matchQuery("method", method);
		}

		if (!StringUtils.isEmpty(ip)) {
			queryBuilder = QueryBuilders.matchQuery("ip", ip);
		}

		if (!StringUtils.isEmpty(queryDate)) {
			Date startDate = DateUtil.toDate(queryDate, "yyyy-MM-dd");
			Date endDate = DateUtil.toDate(queryDate + " 23:59:59",
					"yyyy-MM-dd HH:mm:ss");
			filterBuilder = FilterBuilders.rangeFilter("createdTime")
					.from(startDate.getTime()).to(endDate.getTime());
		}
		Long count = ElasticUtils.getInstance().countIndex(Constants.ELASTIC_INDEX_EX_TRACE,
				queryBuilder, filterBuilder);
		SortBuilder sorBuild = SortBuilders.fieldSort("createdTime").order(
				SortOrder.DESC);
		List<IndexException> result = ElasticUtils.getInstance().queryIndex(
				Constants.ELASTIC_INDEX_EX_TRACE, IndexException.class, queryBuilder,
				filterBuilder, sorBuild, (page - 1) * rows, rows);
		ResultHandler list = new ResultHandler();
		list.setTotal(count.intValue());
		list.setRows(result);
		return list;
	}
}
